﻿using System;
using System.Text;
using System.Web.UI.WebControls;

using Sunyi.Project.WebPoint.BusinessLogic;
using Sunyi.Project.WebPoint.Common;
using Sunyi.Project.WebPoint.Configuration;
using Sunyi.Project.WebPoint.DataContract;
using Sunyi.Project.WebPoint.Resource;
using Sunyi.Project.WebPoint.WebControl;

namespace ActivitySystem.Web.Admin
{
    public partial class RoleEdit : WebPointPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                try
                {
                    BindSystemInfo();

                    if (!string.IsNullOrEmpty(Request.Params[WebPointGlobalConstant.RoleId]))
                    {
                        Guid roleId = new Guid(Request.Params[WebPointGlobalConstant.RoleId]);
                        BindRole(roleId);
                    }
                }
                catch (Exception ex)
                {
                    ExceptionHandler.Handle(this, ex);
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string validationMessage = ValidateParameters();

            if (!string.IsNullOrEmpty(validationMessage))
            {
                this.ShowClientMessage(validationMessage);
                return;
            }

            Role role = null;
            bool isRoleExist = false;
            RoleManager roleManager = new RoleManager();

            try
            {
                if (!string.IsNullOrEmpty(tbxRoleId.Text))
                {
                    role = roleManager.Select(new Guid(tbxRoleId.Text));
                    if (role != null) isRoleExist = true;
                }
                else
                {
                    role = roleManager.SelectByName(tbxRoleName.Text.Trim());

                    if (role == null)
                    {
                        role = new Role();
                        role.Id = Guid.NewGuid();
                    }
                    else
                    {
                        isRoleExist = true;
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(this, ex);
                return;
            }

            role.RoleName = tbxRoleName.Text.Trim();
            role.Description = tbxDescription.Text;
            role.IsActive = Boolean.Parse(ddlStatus.SelectedValue);
            role.SystemId = new Guid(ddlSystem.SelectedValue);

            try
            {
                if (isRoleExist)
                {
                    TransactionHelper.ProcessTransaction(delegate { roleManager.Update(role); if (SystemConfiguration.PersonnelServiceEnabled) roleManager.UploadRoleInfo(role); });

                    AuditLogger.Write(AuditLogOperationCode.Update, this.GetType().Name, role);

                    this.ShowClientMessage(WebResource.OP_UpdateRoleSuccessful);
                    this.ClientRedirect(string.Format(WebPointWebCommon.RedirectUrlFormatRead, this.Request.Path, WebPointGlobalConstant.RoleId, role.Id));
                }
                else
                {
                    TransactionHelper.ProcessTransaction(delegate { roleManager.Insert(role); if (SystemConfiguration.PersonnelServiceEnabled) roleManager.UploadRoleInfo(role); });

                    AuditLogger.Write(AuditLogOperationCode.Create, this.GetType().Name, role);

                    this.ShowClientMessage(WebResource.OP_CreateRoleSuccessful);
                    this.ClientRedirect(string.Format(WebPointWebCommon.RedirectUrlFormatRead, this.Request.Path, WebPointGlobalConstant.RoleId, role.Id));
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(this, ex);
            }
        }

        #region Private Method

        private void BindSystemInfo()
        {
            var systemInfoManager = new SystemInfoManager();
            var systems = systemInfoManager.Search(string.Empty, true, 0, Int32.MaxValue);

            foreach (var systemInfo in systems) ddlSystem.Items.Add(new ListItem(systemInfo.SystemName, systemInfo.Id.ToString()));
        }

        private void BindRole(Guid roleId)
        {
            RoleManager roleManager = new RoleManager();
            Role role = roleManager.Select(roleId);

            if (role != null)
            {
                tbxRoleId.Text = role.Id.ToString();
                tbxRoleName.Text = role.RoleName;
                tbxDescription.Text = role.Description;
                WebPointWebCommon.SetItemSelected(ddlStatus, role.IsActive.ToString());
                WebPointWebCommon.SetItemSelected(ddlSystem, role.SystemId.ToString());
            }
        }

        private string ValidateParameters()
        {
            StringBuilder sb = new StringBuilder();

            if (string.IsNullOrEmpty(tbxRoleName.Text))
            {
                tbxRoleName.BackColor = WebControlCommon.WarningBackColor;
                sb.Append(string.Format(WebResource.FieldValueIsNull, tbxRoleName.ID) + WebPointGlobalConstant.WebEnter);
            }
            else
            {
                tbxRoleName.BackColor = WebControlCommon.DefaultControlBackColor;
            }

            return sb.ToString();
        }

        #endregion

        #region WebPointPage Member

        protected override void ApplyPermission()
        {
            if (!string.IsNullOrEmpty(Request.Params[WebPointGlobalConstant.RoleId]) && !this.HasPermission(PermissionType.Update))
            {
                btnSubmit.Visible = false;
            }

            if (string.IsNullOrEmpty(Request.Params[WebPointGlobalConstant.RoleId]) && !this.HasPermission(PermissionType.Create))
            {
                btnSubmit.Visible = false;
            }

            if (this.RequestPermissionType == PermissionType.Read)
            {
                btnSubmit.Visible = false;
            }
        }

        #endregion
    }
}